/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-shadow */
import React, { Fragment, useEffect, useReducer } from 'react';
import {
  message,
  // Modal, notification
} from 'antd';
import Link from 'umi/link';
import {
  SIZE,
  PAGE,
  BIG_SIZE,
  STUDENT_DOWNLOAD_THEADER,
  STUDENT_DOWNLOAD_FILTER_VALUE,
} from '@/utils/constant';
import {
  studentsList,
  // delStudent
} from '@/services/api';
import StudentsForm from './components/StudentsForm';
import TableList from './components/TableList';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

function StudentsList({ id }: any) {
  const initialState: initial = {
    loading: false,
    data: [],
    pagination: {
      showSizeChanger: true,
    },
    searchValue: { clase_id: id, is_arranged: true },
  };

  const reducer = (state: any, { type, payload }: any) => {
    switch (type) {
      case 'OPEN_LOADING':
        return {
          ...state,
          loading: true,
        };
      case 'CLOSED_LOADING':
        return {
          ...state,
          loading: false,
        };
      case 'GET_DATA':
        return {
          ...state,
          data: payload,
        };
      case 'CHANGE_PAGINATION':
        return {
          ...state,
          pagination: payload,
        };
      case 'SEARCH_VALUE':
        return {
          ...state,
          searchValue: payload,
        };
      default:
        return state;
    }
  };
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    dispatch({
      type: 'OPEN_LOADING',
    });
    studentsList({ ...searchValue, page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  }, []);

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    studentsList({
      ...searchValue,
      page: changePagination.current,
      size: changePagination.pageSize,
    })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  function formatJson(filterVal: string[], jsonData: object[]) {
    return jsonData.map(v => filterVal.map(j => v[j]));
  }

  const downloadData = () => {
    dispatch({
      type: 'OPEN_LOADING',
    });
    studentsList({ ...searchValue, page: PAGE, size: BIG_SIZE })
      .then((res: any) => {
        try {
          const flatArr = res.data.data.map((item: any, index: number) => {
            const cache = {};
            for (const i in item) {
              if (typeof item[i] === 'object') {
                for (const j in item[i]) {
                  if (item[i][j] === 1) {
                    cache[`${i}_${j}`] = '是';
                  } else if (item[i][j] === 0) {
                    cache[`${i}_${j}`] = '否';
                  } else {
                    cache[`${i}_${j}`] = item[i][j];
                  }
                }
              }
            }
            return {
              ...cache,
              ...item,
              index: index + 1,
            };
          });
          import('../../../utils/ExcleTools').then(excel => {
            const tHeader: string[] = STUDENT_DOWNLOAD_THEADER;
            const filterVal: string[] = STUDENT_DOWNLOAD_FILTER_VALUE; // 等后端字段
            const data = formatJson(filterVal, flatArr);

            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '学生报名信息',
            });
          });
        } catch (err) {
          message.error('导出Excel出错!!');
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  const columns = [
    {
      title: '名字',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '父母',
      key: 'parent',
      dataIndex: 'parent',
      render: (text: any) => <span>{text && text.name}</span>,
    },
    {
      title: '老师',
      key: 'teacher',
      dataIndex: 'teacher',
      render: (text: any) => <span>{text && text.name}</span>,
    },
    {
      title: '班级',
      key: 'clase',
      dataIndex: 'clase',
      render: (text: any) => <span>{text && text.name}</span>,
    },
    {
      title: '操作',
      width: 200,
      key: 'option',
      valueType: 'option',
      dataIndex: 'id',
      render: (text: any, object: any) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Link
            to="/applyManage/applyList/detail"
            onClick={() => {
              sessionStorage.setItem('studentsData', JSON.stringify(object));
            }}
          >
            查看详情
          </Link>
          <Link
            to="/teachingSystem/editStudent"
            onClick={() => {
              sessionStorage.setItem('studentsData', JSON.stringify(object));
            }}
          >
            编辑学生
          </Link>
          {/* 说的进了班的学生不允许删除 */}
          {/* <a
            onClick={e => {
              e.preventDefault();
              Modal.confirm({
                content: '确认删除？',
                onOk: () => {
                  delStudent(text).then((resp: any) => {
                    if (resp.data) {
                      notification.success({
                        message: '删除成功',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      studentsList({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }}
          >
            删除
          </a> */}
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <StudentsForm dispatch={dispatch} searchValue={searchValue} downloadData={downloadData} />
      <TableList
        rowKey="id"
        dataSource={data}
        columns={columns}
        loading={loading}
        pagination={pagination}
        onChange={onChange}
      />
    </Fragment>
  );
}

export default StudentsList;
